package com.example.springboot.component;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*登录拦截器
* 功能：拦截所有未登录的访问请求
* 编写好拦截器之后在配置里注册拦截器*/
public class LoginHandleInterceptor implements HandlerInterceptor {
    //在请求前拦截 通过登陆成功 传来的session值来判断是否登录成功
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session里面属性为loginUser的值
        Object user=request.getSession().getAttribute("loginUser");
        if(user==null){
            //未登录
            //我们设置的msg 在标签p里面
            request.setAttribute("msg","未登录请先登录");
            //转到index页面 并传入request response
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }else{
            //已登录 放行请求
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
